package com.circle.rest.core.gmap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.circle.rest.core.common.CommonProperties;
import com.circle.rest.core.gmap.model.District;
import com.circle.rest.core.gmap.model.IpLocation;
import com.circle.rest.core.util.HttpClientUtil;
import com.circle.rest.core.util.ToolUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: ZhaoHang
 * @Date: 2019/4/19 23:15
 * @Description: 高德地图工具类
 */
public class GMapTool {
    private static String districtUrl = "https://restapi.amap.com/v3/config/district";
    private static String ipUrl = "https://restapi.amap.com/v3/ip";


    /**
     * 获取下级行政区域列表
     *
     * @param keywords
     * @return
     */
    public static District getDistricts(String keywords) {
        if (ToolUtil.isEmpty(keywords)) {
            keywords = "100000";
        }
        Map<String, String> map = new HashMap<>();
        map.put("key", CommonProperties.getGMAPKEY());
        map.put("keywords", keywords);
        String resultJson = HttpClientUtil.doGet(districtUrl, map);
        JSONObject jsonObject = JSON.parseObject(resultJson);
        JSONArray districts = jsonObject.getJSONArray("districts");
        JSONObject district = districts.getJSONObject(0);
        return JSON.toJavaObject(district, District.class);
    }

    /**
     * 根据ip获取行政区域
     *
     * @param ip
     * @return
     */
    public static IpLocation getIpLocation(String ip) {
        Map<String, String> map = new HashMap<>();
        map.put("key", CommonProperties.getGMAPKEY());
        map.put("ip", ip);
        String resultJson = HttpClientUtil.doGet(ipUrl, map);
        return JSON.parseObject(resultJson, new TypeReference<IpLocation>() {
        });
    }

}
